# -*- coding: utf-8 -*-
# @Author: Gemini by Tim Liu
# @Date: 2024-10-22
# @Last Modified by: Tim Liu
# @Last Modified time: 2024-10-22

# update by gdf 20241108 修改导入包
# from langchain_core.pydantic_v1 import BaseModel
from pydantic import BaseModel, Field

import smtplib, ssl

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from core.exception import CustomException
#import logging
from utils import status


class EmailInput(BaseModel):
    receiver_email: str = Field(description="Email address to send to. Example: email@example.com")
#    sender_email: str = Field(
#        description="Email address to send from, must be 'validemail@example.com'"
#    )
#    subject: str = Field(description="Email subject")
    body: str = Field(description="Email body text")
    
class MailTool:
    """
    A class for sending emails via SMTP.
    """

    def __init__(self, smtp_server: str = "smtp.exmail.qq.com",
                 port: int = 465, sender_email: str = "tim@swotin.cn",
                 password: str = "Target123"):
        """
        Initializes a MailTool instance.

        Args:
            smtp_server (str, optional): The SMTP server address. Defaults to "smtp.exmail.qq.com".
            port (int, optional): The SMTP port. Defaults to 465.
            sender_email (str, optional): The sender's email address. Defaults to "tim@swotin.cn".
            password (str, optional): The sender's email password. Defaults to "Target123".
        """
        self.smtp_server = smtp_server
        self.port = port
        self.sender_email = sender_email
        self.password = password


    def send_email(self, receiver_email: str, body: str) -> bool:
        """
        Sends an email via SMTP.

        Args:
            receiver_email (str): The recipient's email address.
            body (str): The body of the email.

        Returns:
            bool: True if the email was sent successfully, False otherwise.
        """
        try:
            message = MIMEMultipart("alternative")
            message["Subject"] = "Hey, your copilot has something for you"
            message["From"] = self.sender_email
            message["To"] = receiver_email

            txtbody = MIMEText(body, "plain")
            message.attach(txtbody)

            context = ssl.create_default_context()
            server = smtplib.SMTP_SSL(self.smtp_server, self.port, context=context)
            server.login(self.sender_email, self.password)

            server.sendmail(self.sender_email, receiver_email, message.as_string())
            server.quit()
            
            response = 'Email sent successfully' + ' to ' + receiver_email + ' with content: \n\n' + body

            return response
        except Exception as e:
            raise CustomException(f"Error sending email: {e}", code=status.HTTP_404_NOT_FOUND)
